package br.com.async.application.impl;

import java.security.NoSuchAlgorithmException;
import java.util.List;

import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import br.com.async.application.LoginApplication;
import br.com.async.domain.login.LoginRepository;
import br.com.async.domain.login.User;
import br.com.async.util.Encrypt;

@Transactional(propagation = Propagation.REQUIRED)
public class LoginApplicationImpl implements LoginApplication {

	private LoginRepository loginRepository;
	private Encrypt encrypt;

	public LoginApplicationImpl(LoginRepository loginRepository) {
		super();
		this.encrypt = new Encrypt();
		this.loginRepository = loginRepository;
	}

	@Override
	public User doLogin(String userName, String password) {
		try {
			return loginRepository.doLogin(userName, encrypt.md5(userName+password));
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
		return null;
	}

	@Override
	public void doLogout(User user) {
		loginRepository.doLogout(user);
	}

	@Override
	public void persist(User entity) {
		try {
			entity.setPassword(encrypt.md5(entity.getUserName() + entity.getPassword()));
			loginRepository.persist(entity);
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
	}

	@Override
	public void update(User entity) {
		loginRepository.persist(entity);
	}

	@Override
	public List<User> list() {
		return loginRepository.list();
	}

	@Override
	public void disable(User entity) {
		loginRepository.disable(entity);
	}

	@Override
	public User findByCode(Integer code) {
		return loginRepository.findByCode(code);
	}

}
